<template>
  <div class="aps-section">
    <el-row>
      <span style="font-weight: 600; margin-top: 1px; font-size: large; color: rgb(1, 128, 165);">
        基础参数设定
      </span>
      <!-- 右侧浮动的按钮 -->
      <el-button type="text" style="float: right;" @click="toggleDisplay">
        {{ showParams ? '收起' : '展开' }}
      </el-button>
    </el-row>
    
    <transition name="slide-toggle">
      <div v-show="showParams" style="margin-top: 20px;">
        <el-form 
          :model="formData" 
          label-position="right" 
          label-width="120px" 
          class="params-form"
          :rules="formRules"
          ref="formRef"
        >
          <!-- 基础配置 -->
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="datetime"
              placeholder="选择开始日期"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              style="width: 200px;"
              :clearable="false"
            />
          </el-form-item>
          
          <el-form-item label="生产策略">
            <el-checkbox v-model="formData.workOverTime">
              加班优先
            </el-checkbox>
          </el-form-item>

          <!-- 权重配置区域 -->
          <div class="weight-section">
            <div class="section-header">
              <span class="section-title">权重配置</span>
              <el-tag 
                :type="getWeightSumType()" 
                size="small" 
                class="weight-summary-tag"
              >
                已选权重: {{ getSelectedWeightSum() }}%
              </el-tag>
            </div>
            
            <div class="weight-config-list">
              <!-- 换线次数权重 -->
              <div class="weight-item">
                <div class="weight-row">
                  <el-checkbox 
                    v-model="formData.enableChangeLaneRate"
                    @change="onWeightCheckboxChange('changeLaneRate', $event)"
                    class="weight-checkbox"
                  >
                    换线次数权重
                  </el-checkbox>
                  <div v-if="formData.enableChangeLaneRate" class="weight-input">
                    <el-input-number
                      v-model="formData.changeLaneRate"
                      :min="0"
                      :max="100"
                      :precision="2"
                      placeholder="0.00"
                      size="small"
                      style="width: 120px;"
                      controls-position="right"
                      @change="onWeightValueChange"
                    />
                    <span class="weight-unit">%</span>
                  </div>
                </div>
              </div>

              <!-- 交期权重 -->
              <div class="weight-item">
                <div class="weight-row">
                  <el-checkbox 
                    v-model="formData.enableDeliveryRate"
                    @change="onWeightCheckboxChange('deliveryRate', $event)"
                    class="weight-checkbox"
                  >
                    交期权重
                  </el-checkbox>
                  <div v-if="formData.enableDeliveryRate" class="weight-input">
                    <el-input-number
                      v-model="formData.deliveryRate"
                      :min="0"
                      :max="100"
                      :precision="2"
                      placeholder="0.00"
                      size="small"
                      style="width: 120px;"
                      controls-position="right"
                      @change="onWeightValueChange"
                    />
                    <span class="weight-unit">%</span>
                  </div>
                </div>
              </div>

              <!-- 设备利用率权重 -->
              <div class="weight-item">
                <div class="weight-row">
                  <el-checkbox 
                    v-model="formData.enableEquiptUseProbabilityRate"
                    @change="onWeightCheckboxChange('equiptUseProbabilityRate', $event)"
                    class="weight-checkbox"
                  >
                    设备利用率权重
                  </el-checkbox>
                  <div v-if="formData.enableEquiptUseProbabilityRate" class="weight-input">
                    <el-input-number
                      v-model="formData.equiptUseProbabilityRate"
                      :min="0"
                      :max="100"
                      :precision="2"
                      placeholder="0.00"
                      size="small"
                      style="width: 120px;"
                      controls-position="right"
                      @change="onWeightValueChange"
                    />
                    <span class="weight-unit">%</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 权重提示信息 -->
            <div class="weight-tips">
              <div class="weight-tip-message" :class="getWeightSumType()">
                {{ getWeightTipMessage() }}
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </transition>
  </div>
</template>

<script>
import { ref, reactive, defineComponent, watch } from 'vue'

export default defineComponent({
  name: 'BaseParametersConfig',
  props: {
    modelValue: {
      type: Object,
      default: () => ({
        startDate: '',
        workOverTime: false,
        enableChangeLaneRate: false,
        changeLaneRate: 0,
        enableDeliveryRate: false,
        deliveryRate: 0,
        enableEquiptUseProbabilityRate: false,
        equiptUseProbabilityRate: 0
      })
    },
    collapsed: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'update:collapsed', 'submit'],
  setup(props, { emit }) {
    const formRef = ref(null)
    
    // 控制显示隐藏
    const showParams = ref(!props.collapsed)
    
    
    // 表单数据
    const formData = reactive({
      startDate: props.modelValue?.startDate ,
      workOverTime: props.modelValue?.workOverTime || false,
      enableChangeLaneRate: props.modelValue?.enableChangeLaneRate || false,
      changeLaneRate: props.modelValue?.changeLaneRate || 0,
      enableDeliveryRate: props.modelValue?.enableDeliveryRate || false,
      deliveryRate: props.modelValue?.deliveryRate || 0,
      enableEquiptUseProbabilityRate: props.modelValue?.enableEquiptUseProbabilityRate || false,
      equiptUseProbabilityRate: props.modelValue?.equiptUseProbabilityRate || 0
    })

    // 表单验证规则
    const formRules = {
      startDate: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ]
    }

    // 计算已选择的权重总和
    const getSelectedWeightSum = () => {
      let sum = 0
      if (formData.enableChangeLaneRate) {
        sum += formData.changeLaneRate || 0
      }
      if (formData.enableDeliveryRate) {
        sum += formData.deliveryRate || 0
      }
      if (formData.enableEquiptUseProbabilityRate) {
        sum += formData.equiptUseProbabilityRate || 0
      }
      return sum.toFixed(2)
    }

    // 获取权重总和标签类型
    const getWeightSumType = () => {
      const sum = parseFloat(getSelectedWeightSum())
      if (sum > 100) return 'error'
      if (sum === 100) return 'success'
      if (sum > 80) return 'warning'
      return 'info'
    }

    // 获取权重提示信息
    const getWeightTipMessage = () => {
      const sum = parseFloat(getSelectedWeightSum())
      const enabledCount = [formData.enableChangeLaneRate, formData.enableDeliveryRate, formData.enableEquiptUseProbabilityRate].filter(Boolean).length
      
      if (enabledCount === 0) {
        return '请至少选择一个权重配置项'
      }
      if (sum > 100) {
        return `权重总和 ${sum}% 超过100%，请调整权重配置`
      }
      if (sum === 100) {
        return '权重配置完美，总和为100%'
      }
      if (sum > 80) {
        return `权重配置良好，当前总和为 ${sum}%`
      }
      return `当前权重总和为 ${sum}%，建议调整至100%`
    }

    // 权重复选框变化处理
    const onWeightCheckboxChange = (weightType, checked) => {
      if (!checked) {
        // 取消勾选时，重置对应权重值
        formData[weightType] = 0
      }
      // 不需要立即调用 updateFormData，watch 会自动处理
    }

    // 权重值变化处理
    const onWeightValueChange = () => {
      // 不需要立即调用 updateFormData，watch 会自动处理
    }

    // 切换显示状态
    const toggleDisplay = () => {
      showParams.value = !showParams.value
      emit('update:collapsed', !showParams.value)
    }

    // 监听表单数据变化，向父组件发送更新事件
    const updateFormData = () => {
      emit('update:modelValue', { ...formData })
    }

    // 监听props变化，更新内部数据
    const loadData = (data) => {
      Object.assign(formData, data)
    }

    // 获取表单数据
    const getFormData = () => {
      return { ...formData }
    }

    // 验证表单
    const validateForm = async () => {
      if (!formRef.value) return { valid: false, errors: ['表单引用不存在'] }
      
      try {
        await formRef.value.validate()
        
        // 验证权重配置
        const sum = parseFloat(getSelectedWeightSum())
        if (sum > 100) {
          return { valid: false, errors: ['权重总和不能超过100%'] }
        }
        
        return { valid: true, errors: [] }
      } catch (error) {
        return { valid: false, errors: ['表单验证失败'] }
      }
    }


    // 暴露方法给父组件
    const exposed = {
      getFormData,
      loadData,
      validateForm,
      toggleDisplay
    }

    // 监听formData变化
    watch(
      () => ({ ...formData }),
      () => {
        updateFormData()
      },
      { deep: true, flush: 'post' }
    )

    // 监听props变化
    watch(
      () => props.modelValue,
      (newValue) => {
        if (newValue && Object.keys(newValue).length > 0) {
          Object.assign(formData, newValue)
        }
        console.log("watch2",newValue)
      },
      { deep: true, immediate: true }
    )

    return {
      formRef,
      showParams,
      formData,
      formRules,
      toggleDisplay,
      updateFormData,
      getSelectedWeightSum,
      getWeightSumType,
      getWeightTipMessage,
      onWeightCheckboxChange,
      onWeightValueChange,
      ...exposed
    }
  }
})
</script>

<style scoped>
.aps-section {
  background-color: #ebebeb;
  padding: 15px;
  margin-top: 20px;
  border-radius: 5px;
}

.slide-toggle-enter-active,
.slide-toggle-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-toggle-enter,
.slide-toggle-leave-to {
  max-height: 0;
  opacity: 0;
}

.slide-toggle-enter {
  max-height: 0;
}

.slide-toggle-leave-to {
  max-height: 0;
}

/* 表单样式 */
.params-form {
  margin-bottom: 20px;
}

/* 权重配置区域 */
.weight-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-weight: 600;
  color: rgb(1, 128, 165);
  font-size: 14px;
}

.weight-summary-tag {
  font-weight: 500;
}

/* 权重配置列表 */
.weight-config-list {
  margin-bottom: 15px;
}

.weight-item {
  margin-bottom: 10px;
}

.weight-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
}

.weight-checkbox {
  font-weight: 500;
  color: #495057;
}

.weight-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.weight-unit {
  color: #6c757d;
  font-size: 12px;
  font-weight: 500;
}

/* 权重提示信息 */
.weight-tips {
  margin-top: 15px;
}

.weight-tip-message {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.weight-tip-message.info {
  background-color: #e1f5fe;
  color: #01579b;
  border: 1px solid #b3e5fc;
}

.weight-tip-message.warning {
  background-color: #fff3e0;
  color: #e65100;
  border: 1px solid #ffcc02;
}

.weight-tip-message.success {
  background-color: #e8f5e8;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

.weight-tip-message.error {
  background-color: #ffebee;
  color: #c62828;
  border: 1px solid #ffcdd2;
}


/* 保持与现有组件一致的表单标签样式 */
:deep(.el-form-item__label) {
  color: #714B67 !important;
  font-weight: 600;
}

/* 复选框样式 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #714B67;
  border-color: #714B67;
}

:deep(.el-checkbox__inner:hover) {
  border-color: #714B67;
}

/* 按钮样式 */
.idoo-details-button {
  background-color: rgb(1, 128, 165);
  border-color: rgb(1, 128, 165);
  color: white;
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.idoo-details-button:hover {
  background-color: rgb(1, 108, 145);
  border-color: rgb(1, 108, 145);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .weight-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>